package org.ricks.action.rpc;

import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.session.TcpSessionAdapter;
import org.ricks.net.action.parser.ProtocolParserEnum;
import org.ricks.net.action.context.head.RpcHeadMeta;
import org.ricks.net.extension.protocol.FixedLengthBytesProtocol;
import org.ricks.net.transport.AioSession;

import java.nio.ByteBuffer;

public class RpcProtocol extends FixedLengthBytesProtocol<FlowContext<RpcHeadMeta>> {
    @Override
    protected FlowContext<RpcHeadMeta> decode(byte[] bytes, AioSession session) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        short cmd = byteBuffer.getShort();
        byte mark = byteBuffer.get();
        int msgId = byteBuffer.getInt();
        byte[] data = new byte[byteBuffer.remaining()];
        byteBuffer.get(data);
        // 修复：使用位运算提取响应标志 (次高位 0x40)
        boolean isResponse = (mark & 0x40) != 0; // ✅ 正确解析次高位
        RpcHeadMeta rpcHeadMeta = new RpcHeadMeta(cmd,isResponse,false, msgId);
        return new FlowContext<>(new TcpSessionAdapter(session, ProtocolParserEnum.STRING.getParser()),rpcHeadMeta,data,
                ProtocolParserEnum.STRING.getParser());
    }
}
